<template>
  <!-- 根元素 div，确保组件结构正确 -->
  <div>
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">订单信息</span>
          <div class="tabs">
            <!-- 按钮样式修正：激活时使用 'primary' (蓝色) -->
            <el-button
              v-for="(item, index) in tabList"
              :key="item.value"
              :type="activeIndex === index ? 'primary' : 'default'"
              @click="handleTabClick(index, item.value)"
            >
              {{ item.label }}
              <el-badge
                v-if="item.num > 0"
                :value="item.num"
                :max="99"
                class="tab-badge"
              />
            </el-button>
          </div>
        </div>
      </template>

      <!-- 表格内容 -->
      <div v-if="orderData.length > 0">
        <el-table :data="orderData" stripe style="width: 100%" @row-click="handleRowClick">
          <el-table-column prop="number" label="订单号" min-width="180" />
          <el-table-column label="订单菜品" min-width="160">
            <template #default="{ row }">
              <el-tooltip :content="row.orderDishes" placement="top">
                <span class="ellipsis">{{ row.orderDishes }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="地址" min-width="180">
            <template #default="{ row }">
              <el-tooltip :content="row.address" placement="top">
                <span class="ellipsis">{{ row.address }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            prop="estimatedDeliveryTime"
            label="预计送达时间"
            sortable
            min-width="160"
          />
          <el-table-column prop="amount" label="实收金额" width="100">
            <template #default="{ row }">
              <span>¥{{ row.amount.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="120">
            <template #default="{ row }">
              <el-tooltip :content="row.remark" placement="top">
                <span class="ellipsis">{{ row.remark }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="150"
          >
            <template #default="{ row }">
              <el-button v-if="row.status === 2" type="primary" link @click.stop="acceptOrder(row)">
                接单
              </el-button>
              <el-button v-if="row.status === 3" type="primary" link @click.stop="dispatchOrder(row)">
                派送
              </el-button>
              <el-button v-if="row.status === 2" type="danger" link @click.stop="showRejectDialog(row)">
                拒单
              </el-button>
              <el-button type="info" link @click.stop="viewDetails(row)">
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-if="totalCount > pageSize"
          class="pagination"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-container">
        <el-empty description="当前分类下暂无订单" />
      </div>
    </el-card>

    <!-- 拒单对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      :title="cancelDialogTitle + '原因'"
      width="500px"
      @close="resetCancelDialog"
    >
      <el-form>
        <el-form-item :label="cancelDialogTitle + '原因：'">
          <el-select v-model="cancelReason" placeholder="请选择原因" style="width: 100%">
            <el-option
              v-for="item in rejectionReasonList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="cancelReason === '自定义原因'" label="自定义原因：">
          <el-input
            v-model.trim="customRemark"
            type="textarea"
            :placeholder="'请填写原因（20字内）'"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReject">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import {
  getOrderPage,
  confirmOrder,
  rejectOrder,
  deliverOrder,
} from '@/api/order';

// --- Props & Emits ---
const props = withDefaults(defineProps<{
  orderStatics: {
    waitingOrders?: number;
    deliveredOrders?: number;
  };
}>(), {
  orderStatics: () => ({
    waitingOrders: 0,
    deliveredOrders: 0
  })
});

const emit = defineEmits(['getOrderListBy3Status']);

// --- 状态管理 (Refs) ---
const activeIndex = ref(0);
const currentStatus = ref(2); // 默认查询 "待接单"
const orderData = ref<any[]>([]);
const page = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);
const cancelDialogVisible = ref(false);
const cancelDialogTitle = ref('');
const cancelReason = ref('');
const customRemark = ref('');
const activeOrder = ref<any>(null);

// --- 计算属性 ---
const tabList = computed(() => [
  { label: '待接单', value: 2, num: props.orderStatics.waitingOrders || 0 },
  { label: '待派送', value: 3, num: props.orderStatics.deliveredOrders || 0 },
]);

const rejectionReasonList = [
  { value: 1, label: '订单量较多，暂时无法接单' },
  { value: 2, label: '菜品已售完，暂时无法接单' },
  { value: 3, label: '餐厅已打烊，暂时无法接单' },
  { value: 0, label: '自定义原因' },
];

// --- API & 事件处理 ---
const fetchOrderData = async () => {
  try {
    const params = { page: page.value, pageSize: pageSize.value, status: currentStatus.value };
    const response = await getOrderPage(params);
    if (response.code === 1 && response.data) {
      orderData.value = response.data.records;
      totalCount.value = response.data.total;
    } else {
      ElMessage.error(response.msg || '获取订单数据失败');
    }
  } catch (error) {
    console.error("获取订单数据失败:", error);
    ElMessage.error('网络错误，请稍后重试');
  }
  // 在获取数据后触发事件，通知父组件更新统计（如果需要的话）
  emit('getOrderListBy3Status');
};

const handleTabClick = (index: number, status: number) => {
  activeIndex.value = index;
  currentStatus.value = status;
  page.value = 1; // 切换分类时重置到第一页
  fetchOrderData();
};

const acceptOrder = async (row: any) => {
  try {
    const res = await confirmOrder({ id: row.id });
    if (res.code === 1) {
      ElMessage.success('接单成功！');
      fetchOrderData(); // 成功后刷新列表
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
     ElMessage.error('操作失败');
  }
};

const dispatchOrder = async (row: any) => {
  try {
    const res = await deliverOrder(row.id);
    if (res.code === 1) {
      ElMessage.success('派送成功！');
      fetchOrderData(); // 成功后刷新列表
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error('操作失败');
  }
}

const showRejectDialog = (row: any) => {
  activeOrder.value = row;
  cancelDialogTitle.value = '拒绝';
  cancelDialogVisible.value = true;
};

const confirmReject = async () => {
  if (!cancelReason.value) {
    return ElMessage.warning('请选择原因');
  }
  if (cancelReason.value === '自定义原因' && !customRemark.value) {
    return ElMessage.warning('请填写自定义原因');
  }

  const reason = cancelReason.value === '自定义原因' ? customRemark.value : cancelReason.value;

  try {
    const res = await rejectOrder({ id: activeOrder.value.id, rejectionReason: reason });
    if (res.code === 1) {
      ElMessage.success('拒单成功');
      cancelDialogVisible.value = false;
      fetchOrderData(); // 成功后刷新列表
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

const resetCancelDialog = () => {
  activeOrder.value = null;
  cancelReason.value = '';
  customRemark.value = '';
};

// 查看详情 (可根据需求实现路由跳转或弹窗)
const viewDetails = (row: any) => {
  console.log('查看详情:', row);
  ElMessage.info('查看详情功能待实现');
};

const handleRowClick = (row: any) => {
  viewDetails(row);
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchOrderData();
};
const handleCurrentChange = (val: number) => {
  page.value = val;
  fetchOrderData();
};

// --- 生命周期钩子 ---
onMounted(() => {
  // 组件挂载后，自动获取第一页的“待接单”数据
  fetchOrderData();
});
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;

  .title {
    font-size: 16px;
    font-weight: 600;
  }

  .tabs {
    display: flex;
    gap: 10px;

    .tab-badge {
      margin-left: 8px;
    }
  }
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 250px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
